<template>
  <view class="content" v-if="firstApp">
    <!-- #ifdef MP-WEIXIN -->
    <view
      v-if="isSticky"
      class="todo-head"
      :style="{
        height: menu.height + 'px',
        lineHeight: menu.height + menu.top + 'px',
      }"
    >
      首页
    </view>
    <!-- #endif -->
    <batten @on-login="userLoginDialog = true" />
    <view class="doings-box">
      <view class="doing-tip" />
      <up-swiper
        :list="activityData"
        keyName="eventsPicture"
        indicator
        indicatorMode="line"
        imgMode="widthFix"
        circular
        @click="handleActivitySwiperItemClick"
      />
    </view>
    <view class="list">
      <view class="list-top">
        <text class="header-title">榜单</text>
        <text
          v-if="isEmpty(curArea)"
          class="area"
          @tap="handleMoreAreaBtnClick"
        >
          区域选择 >
        </text>
        <text v-else class="area" @tap="handleMoreAreaBtnClick">
          {{ curArea }} >
        </text>
      </view>
      <view class="tabs-box">
        <up-sticky :offset-top="top_height">
          <up-tabs
            :line-height="rpx2px(20)"
            lineColor="#00B588"
            :itemStyle="listTabStyle"
            :list="listTabsDataList"
            @change="handleListTabChange"
            :activeStyle="{
              color: '#303133',
              fontWeight: 'bold',
              transform: 'scale(1.05)',
            }"
          />
        </up-sticky>
        <billboard
          v-if="billboardData.length > 0"
          :typeName="typeName"
          :list-data="billboardData"
          @on-click="onBillboard"
        />
      </view>
    </view>
    <none-data v-if="billboardData.length === 0 && isLoading" />
    <!-- <uni-popup ref="overlay" :before-close="true" background-color="#fff">
      <view class="popup-content">
        <view class="wrapper">
          <view class="cancellation-box">
            <view class="cancellation">
              <view class="name">绑定手机号</view>
              <view class="text-box">
                <text style="color: #00b588">{{ name }} </text>
                该账号未绑定手机号，请进行手机号绑定
              </view>
              <view class="tail" @click="lookClick">
                <text>去绑定</text>
              </view>
            </view>
            <view class="close-btn" @click="closeClick">X</view>
          </view>
        </view>
      </view>
    </uni-popup> -->
    <!--啤酒节弹窗-->
    <custom-dialog
      v-if="popDialogShowFlag"
      :title="activity?.title"
      @close-btn-click="handleDialogCloseBtnClick"
      calssName="notification"
    >
      <view class="text-content">
        <view class="img_box">
          <image style="width: 100%;" class="img" mode="widthFix" :src="activity?.disposeResourceUrl"> </image>
        </view>
        <!-- <text class="text"> 盛夏激情，荣耀高兴！ </text>
        <text class="text">
          企业进驻，最高享
          <text class="special">八八折</text>
          优惠
        </text>
        <text class="text"> 扫码更能获"足"梦高新专属徽章！ </text> -->
      </view>
      <view class="btn-group">
        <!-- <text class="btn">加入指引</text> -->
        <text class="btn" @tap="joinClick">去加入</text>
      </view>
      <!-- <view class="close-btn" @click="popDialogShowFlag = false">X</view> -->
    </custom-dialog>
    <!--区域选择弹窗-->
    <up-popup
      class="more-area-popup"
      :show="moreAreaPopupData.display"
      :round="rpx2px(33)"
      :safeAreaInsetBottom="false"
      mode="bottom"
      @close="moreAreaPopupClose"
    >
      <view>
        <view class="more-area-popup">
          <text class="title"> 区域选项 </text>
          <up-grid :border="false" col="4">
            <up-grid-item
              v-for="(area, index) in moreAreaPopupData.areaList"
              :key="index"
              @tap="handleMoreAreaPopupAreaClick(area)"
            >
              <text
                :class="['area-normal', area.isSelected ? 'area-selected' : '']"
                >{{ area.areaName }}</text
              >
            </up-grid-item>
          </up-grid>
          <view class="btn-group">
            <view class="btn clear" @tap="handleMoreAreaClearBtnClick"
              >清除</view
            >
            <view class="btn sure" @tap="handleMoreAreaSureBtnClick">确定</view>
          </view>
        </view>
      </view>
    </up-popup>
    <!-- 登录弹窗 -->
    <loginDialog @on-off="userLoginDialog = false" @on-make="headelMake" :indicate="userLoginDialog">
    </loginDialog>
  </view>
</template>

<script setup>
import batten from "./componts/batten.vue";
import billboard from "@/components/billboard/index.vue";

import {
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  ref,
  watch,
} from "vue";
import {
  getActivityDataApi,
  getListDataApi,
  getMoreAreaDataApi,
  userGetBadgeApi,
  getActivityPopupApi,
  isShowActivityPopupApi,
} from "@/api/index/index.js";
import { getUserInfoApi } from "@/api/public/index.js";
import { onBackPress, onLoad, onPageScroll, onShow } from "@dcloudio/uni-app";
import { useFormatDate } from "@/utils/formatHooks";
import {
  rpx2px,
  wxGetSafeTopHeight,
  wxSetUpShareFunction,
} from "@/utils/utils";
import { customNav } from "@/utils/customNav";
import { isEmpty } from "@/utils/is";
import { checkUserHasPhoneApi } from "../../api/index";
import CustomDialog from "@/components/CustomDialog";
import loginDialog from "@/components/login/index.vue";

const { proxy } = getCurrentInstance();

const userLoginInfo = ref("");
const userLoginDialog = ref(false);
const show = ref(false);
const name = ref("");
const top_height = wxGetSafeTopHeight();
console.log(top_height);

const activity = ref({});
// 活动轮播图数据
const activityData = ref([]);
/**
 * 获取活动轮播图
 * @returns {Promise<void>}
 */
const getActivityData = async () => {
  const res = await getActivityDataApi();
  const { code, data } = res;
  if (code === 200) {
    console.log(data);
    activityData.value = data;
  }
};
// 活动包地址
const packageActivityPath = inject("packageActivityPath");
/**
 * 活动swiper点击事件监听
 * @param idx
 */
const handleActivitySwiperItemClick = (idx) => {
  const data = activityData.value[idx]
  console.log(data.rule)
  if(data.entrance === 'activity_refuel') {
    customNav("/package_refuel/pages/index");
  } else if(data.entrance === 'activity_gqj_sctp') {
    customNav("/package_games/pages/nationalDay");
  } else if(data.entrance === 'activity_gqj_dt') {
    customNav("/package_games/pages/nationalDayAnswer");
  } else if(data.entrance === 'activity_coupon') {
    customNav("/package_coupon/pages/list");
  } else if(data.entrance !== '' && data.entrance !== null) {
    if(data.rule === '投票活动') {
      uni.navigateTo({
        url:`${packageActivityPath}/activity/activity-user-info?isVote=1&id=${activityData.value[idx].entrance}`
      })
    }
    /*else if(data.rule === '打卡挑战') {
      uni.navigateTo({
        url:`${packageActivityPath}/activity/activity-progress?isVote=1&id=${activityData.value[idx].entrance}`
      })
    } */
    else {
      uni.navigateTo({
        url:`${packageActivityPath}/activity-detail?isVote=1&id=${activityData.value[idx].entrance}`
      })
    }
  }

  // customNav(`${packageActivityPath}/activity-detail?id=` + activityData.value[idx].entrance);

  // const findItem = activityData.value[idx];
  // const posterImgUrl = findItem?.placard;
  // customNav(
  //   `${packageActivityPath}/activity-poster?posterImgUrl=${posterImgUrl}`
  // );
};
// const ceshi = () => {
//   customNav(`/package_payment/pages/index?shops_code=1`);
// };

const typeName = ref("企业");
const billboardData = ref([]);
const listTabStyle = {
  flex: 1,
  fontFamily: "ali-p",
  fontSize: "31rpx",
  height: "80rpx!important",
};
const listTabsDataList = ref([
  {
    name: "荣誉总榜",
    id: "4",
  },
  {
    name: "热搜榜",
    id: "0",
  },
  {
    name: "创新发展榜",
    id: "5",
  },
  {
    name: "公司治理榜",
    id: "6",
  },
  {
    name: "市场营销榜",
    id: "7",
  },
  {
    name: "团队建设榜",
    id: "8",
  },
  {
    name: "安全生产榜",
    id: "9",
  },
  {
    name: "社会责任榜",
    id: "10",
  },
]);
const isSticky = ref(false);
const stickyTop = ref(0);
const menu = reactive({
  height: 0,
  top: 0,
  tabTop: 0,
  platform: 0, //1：代表微信小程序，0：其他
});

const curArea = ref("贵阳国家高新区");
watch(curArea, () => {
  getListData();
});
// 区域选择弹窗
const moreAreaPopupData = reactive({
  display: false,
  areaList: [],
});
const getMoreAreaData = async () => {
  const res = await getMoreAreaDataApi();
  const { code, data } = res;
  if (code === 200) {
    const moreAreaData = data.find(
      (item) => item.filedName === "荣誉区域"
    )?.children;

    moreAreaPopupData.areaList = moreAreaData.map((subItem) => {
      return {
        areaName: subItem.filedName,
        isSelected: curArea.value == subItem.filedName ? true : false,
      };
    });
  }
};
const handleMoreAreaBtnClick = async () => {
  moreAreaPopupData.display = true;
};
/**
 * 更多区域弹窗关闭事件
 */
const moreAreaPopupClose = () => {
  moreAreaPopupData.display = false;
};
/**
 * 登录弹窗关闭事件
 */
const headelMake = () => {
  userLoginDialog.value = false;
  userLoginInfo.value = uni.getStorageSync("token");
};
/**
 * 更多区域弹窗区域item点击事件
 * @param area
 */
const handleMoreAreaPopupAreaClick = (area) => {
  const selectedArea = moreAreaPopupData.areaList.find(
    (item) => item.isSelected
  );
  if (!selectedArea || area.areaName !== selectedArea.areaName) {
    moreAreaPopupData.areaList.forEach((item) => (item.isSelected = false));
    area.isSelected = true;
  }
};
/**
 * 更多区域弹窗清除按钮点击事件监听
 */
const handleMoreAreaClearBtnClick = () => {
  console.log(moreAreaPopupData.areaList);
  moreAreaPopupData.areaList.forEach((item) =>
    item.areaName !== "贵阳市"
      ? (item.isSelected = false)
      : (item.isSelected = true)
  );
};

const handleMoreAreaSureBtnClick = () => {
  curArea.value =
    moreAreaPopupData.areaList.find((item) => item.isSelected)?.areaName || "";
  moreAreaPopupData.display = false;
};

const curTabId = ref("4");
watch(curTabId, () => {
  getListData();
});
/**
 * 榜单tabChange事件监听
 * @param tab
 */
const handleListTabChange = (tab) => {
  curTabId.value = tab.id;
  // getListData(tab.id)
};
/**
 * 获取榜单列表数据
 * @returns {Promise<void>}
 */
const getListData = async () => {
  const res = await getListDataApi(curTabId.value, curArea.value);
  let { code, data } = res;
  if (code === 200) {
    isLoading.value = true;
    if(data != null && data.length > 10) {
      data = data.slice(0, 10);
    }
    billboardData.value = data.map((o) => {
      return {
        id: o.id,
        name: o.hotName,
        deputy: o.legalRepresentative,
        counties: o.counties,
        time: useFormatDate(o.createTime),
        total: o.total,
        showScore: curTabId.value !== "0",
      };
    });
  }
};
const firstApp = ref(false);
const isLoading = ref(false);

function onBillboard(data) {
  /*if (!userLoginInfo.value) {
    userLoginDialog.value = true;
  } else {*/
    customNav(
      `/package_honour/pages/honour/enterprise-honor-detail?name=${data.name}&&typeName=${typeName.value}&&id=${data.id}`
    );
  // }
}

// function lookClick() {
//   // customNav('/pages/index/merge')
// }

// function closeClick() {
//   // console.log("ssssssssssssssssssss");
//   proxy.$refs.overlay.close();
// }

const popDialogShowFlag = ref(false);
const userInfo = ref({});
const getUserInfo = async () => {
  /*const res = await getUserInfoApi();
  const { code, data } = res;
  if (code === 200) {
    userInfo.value = data;
    // const { enterpriseManger: isEnterpriseManger } = data;
    // popDialogShowFlag.value = !isEnterpriseManger;
  }*/
};
const handleDialogCloseBtnClick = () => {
  popDialogShowFlag.value = false;
};
// const useGetBadge = async () => {
//   await userGetBadgeApi();
// };

const checkUserHasPhone = async () => {
  const res = await checkUserHasPhoneApi();
  const { code, data } = res;
  if (code === 200) {
    console.log(data, "JIAN");
  }
};
// 活动弹窗内容
const getActivityPopupData = async () => {
  const res = await getActivityPopupApi();
  const { code, data } = res || {};
  if (code == 200) {
    if (data.length !== 0) {
      activity.value = data[0];
      popDialogShowFlag.value = true;
    }
  }
};

// 活动弹窗内容
const isShowActivityPopupData = async () => {
  const res = await isShowActivityPopupApi();
  let { code, success } = res || {};
  if (success) {
    getActivityPopupData();
  }
};
const joinClick = () => {
  customNav(
    `/package_activity/pages/activity-detail?id=${activity.value.activityId}`
  );
};

onShow(() => {
  // uni.removeStorageSync("token");
  userLoginInfo.value = uni.getStorageSync("token");
  getActivityData();
  getListData();
  getMoreAreaData();
  firstApp.value = true;
  if (!userLoginInfo.value) {
  } else {
    getUserInfo();
    checkUserHasPhone();
    isShowActivityPopupData();
  }
  // useGetBadge()
  // getUserMergeDataApi().then((res) => {
  stickyTop.value = uni.upx2px(1000);
  // #ifdef MP-WEIXIN
  wxSetUpShareFunction(`/pages/index/index`);
  let rect = uni.getMenuButtonBoundingClientRect();
  menu.height = rect.height + rect.top;
  menu.top = rect.top;
  menu.tabTop = rect.height + rect.top;
  menu.platform = 1;
  // #endif
});

onPageScroll((e) => {
  isSticky.value = e.scrollTop > stickyTop.value;
});
// onBackPress((options) => {
//   alert(options)
// })
// const moveHandle = () => {};
</script>

<style lang="less" scoped>
@import "@/static/style/global.less";
@import "./style/index.less";
</style>
